package com.example.duihua.controller;

import com.example.duihua.entity.Message;
import com.example.duihua.entity.User;
import com.example.duihua.service.MessageService;
import com.example.duihua.service.UserService;
import com.example.duihua.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;
    
    @Autowired
    private UserService userService;

    @GetMapping("/private/{userId}")
    public ResponseEntity<?> getPrivateMessages(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        // 从UserDetails中获取当前用户名
        String username = userDetails.getUsername();
        // 这里需要通过用户名获取用户ID，假设有一个方法可以做到这一点
        Long currentUserId = getUserIdByUsername(username);
        
        List<Message> messages = messageService.getPrivateMessages(currentUserId, userId, page, size);
        // 统一 conversationId，私聊用有序对（min_max），便于任意一方匹配
        Long a = Math.min(currentUserId, userId);
        Long b = Math.max(currentUserId, userId);
        String convId = "private_" + a + "_" + b;
        for (Message m : messages) {
            m.setConversationId(convId);
        }
        return ResponseEntity.ok(ApiResponse.success(messages));
    }

    @GetMapping("/group/{groupId}")
    public ResponseEntity<?> getGroupMessages(
            @PathVariable Long groupId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        List<Message> messages = messageService.getGroupMessages(groupId, page, size);
        for (Message m : messages) {
            m.setConversationId("group_" + groupId);
        }
        return ResponseEntity.ok(ApiResponse.success(messages));
    }

    @PostMapping("/read")
    public ResponseEntity<?> markMessagesAsRead(@RequestBody Map<String, List<Long>> request) {
        List<Long> messageIds = request.get("messageIds");
        boolean success = messageService.markAsRead(messageIds);
        return ResponseEntity.ok(ApiResponse.success(success));
    }

    @DeleteMapping("/{messageId}")
    public ResponseEntity<?> recallMessage(
            @PathVariable Long messageId,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        // 从UserDetails中获取当前用户名
        String username = userDetails.getUsername();
        // 这里需要通过用户名获取用户ID
        Long currentUserId = getUserIdByUsername(username);
        
        boolean success = messageService.recallMessage(messageId, currentUserId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("消息已撤回"));
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.error("无法撤回消息"));
        }
    }
    
    // 辅助方法：通过用户名获取用户ID
    private Long getUserIdByUsername(String username) {
        User user = userService.findByUsername(username);
        if (user != null) {
            return user.getId();
        }
        throw new RuntimeException("用户不存在: " + username);
    }
}